import pos from 'api/pos'
import {InputWithIcon, RadiusButton, Toast} from 'components'
import Loading from 'components/loading'
import React, {useEffect, useState, useRef} from 'react'
import {BackHandler, Image, Platform, ScrollView, Text, View, Alert} from 'react-native'
import {NavigationStackScreenComponent} from 'react-navigation-stack'
import {getAuthorization, loginOut, setLogin} from 'services/authorization'
import {navigate, navigateReplace} from 'services/navigation'
import {commonStyle, definedColors, translateSize} from 'styles'

import assets from './assets'
import {signInStyle} from './styles'

const md5 = require('blueimp-md5')

const SignInScreen: NavigationStackScreenComponent = props => {
  const [useName, setUserName] = useState<string>('admin')
  const [password, setPassword] = useState<string>('123456')
  // const [lastBackPressed, setLastBackPressed] = useState<number>(0)
  let lastBackPressed = useRef<number>()
  const onBackAndroid = () => {
    // Alert.alert(`${lastBackPressed}`)
    if (props.navigation.isFocused()) {
      //判断   该页面是否处于聚焦状态
      if (lastBackPressed && lastBackPressed + 2000 >= Date.now()) {
        // 最近2秒内按过back键，可以退出应用。
        // return false;
        // BackHandler.exitApp();//直接退出APP
        return false
      } else {
        lastBackPressed = Date.now()
        Toast.show('再按一次退出应用')
        // 提示
        return true
      }
    }

    // Alert.alert('确认', '确认删除该用户', [{
    // 	text: "确认", onPress: () => {
    // 		lastBackPressed = 1;
    // 		console.log(lastBackPressed)
    // 		return lastBackPressed
    // 	}
    // }, {
    // 	text: "取消", onPress: () => {
    // 		lastBackPressed = 0
    // 		console.log(lastBackPressed)
    // 		return lastBackPressed
    // 	}
    // }])
  }

  useEffect(() => {
    if (Platform.OS === 'android') {
      BackHandler.addEventListener('hardwareBackPress', onBackAndroid)
    }
    return () => {
      if (Platform.OS === 'android') {
        BackHandler.removeEventListener('hardwareBackPress', onBackAndroid)
      }
    }
  }, [])

  useEffect(() => {
    let ss: any
    if (Platform.OS === 'android') {
      ss = props.navigation.addListener('willBlur', () => {
        BackHandler.removeEventListener('hardwareBackPress', onBackAndroid)
      })
    }
    return () => {
      if (Platform.OS === 'android') {
        ss && ss.remove()
      }
    }
  }, [])

  useEffect(() => {
    let ss: any
    if (Platform.OS === 'android') {
      ss = props.navigation.addListener('willFocus', () => {
        BackHandler.addEventListener('hardwareBackPress', onBackAndroid)
      })
    }
    return () => {
      if (Platform.OS === 'android') {
        ss && ss.remove()
      }
    }
  }, [])

  return (
    <ScrollView style={commonStyle.containerColumn} keyboardShouldPersistTaps="always">
      <View style={signInStyle.logoContainer}>
        <Image source={assets.images.red_circle} style={signInStyle.redCircleLeft} />
        <Image source={assets.images.red_circle} style={signInStyle.redCircleRight} />
        <Image source={assets.images.logo} style={signInStyle.logo} />
        <View style={signInStyle.welcomeContainer}>
          <Text style={signInStyle.welcomeTitle}>WELCOME!</Text>
          <Image source={assets.images.welcome_arrow} style={signInStyle.welcomeArrow} />
        </View>
      </View>
      <View
        style={{
          ...commonStyle.containerColumn,
          ...{alignItems: 'center', paddingHorizontal: translateSize(32), backgroundColor: '#fff'},
        }}>
        <InputWithIcon
          style={{marginTop: translateSize(150)}}
          icon={assets.images.user_name}
          textContentType="none"
          placeholder="请输入账号"
          onChange={setUserName}
        />
        <InputWithIcon
          icon={assets.images.user_password}
          textContentType="password"
          placeholder="请输入密码"
          onChange={setPassword}
        />
        <RadiusButton
          style={{
            marginTop: translateSize(280),
            height: translateSize(96),
          }}
          onPress={() => {
            if (useName === '') {
              Toast.show('请输入用户名')
              return
            }
            if (password === '') {
              Toast.show('请输入密码')
              return
            }
            Loading.show()
            loginOut()
            pos.public.posApp
              .login({
                account: useName,
                password: password,
                mac: '00-00',
                // mac: getAuthorization().mac,
                // version: getAuthorization().version,
              })
              .then(res => {
                if (res.result) {
                  setLogin(res.data)
                  navigateReplace('AppHome')
                  // props.navigation.navigate('AppHome')
                } else {
                  Toast.show(res.msg || '登录失败，请稍后再试')
                }
              })
              .catch(err => {
                Toast.show(err.msg ? err.msg : '登录失败，请稍后再试')
              })
              .finally(() => {
                Loading.hide()
              })
          }}>
          <Text
            style={{
              color: definedColors.white,
              fontSize: translateSize(28),
            }}>
            登录
          </Text>
        </RadiusButton>
      </View>
    </ScrollView>
  )
}

SignInScreen.navigationOptions = props => {
  return {header: null}
}
export default SignInScreen
